﻿using System;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace ViCode_LeVi.Controls.Converters
{
    public class BinaryToImageConverter : IValueConverter
    {
        #region IValueConverter Members

        // cheat sql server
        //private readonly static byte[] hdrdefault = new byte[] {
        //    0x15, 0x1C, 0x2F, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x0E, 0x00, 0x14, 0x00, 0x21, 0x00,
        //    0xFF, 0xFF, 0xFF, 0xFF, 0x42, 0x69, 0x74, 0x6D, 0x61, 0x70, 0x20, 0x49, 0x6D, 0x61, 0x67, 0x65,
        //    0x00, 0x50, 0x61, 0x69, 0x6E, 0x74, 0x2E, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x00, 0x01,
        //    0x05, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x50, 0x42, 0x72, 0x75, 0x73,
        //    0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0x29, 0x00, 0x00,
        //};

        // de viet Converter hien thi hinh
        public static BitmapImage SqlImageToBitmapImage(byte[] data)
        {
            if (data == null || data.Length == 0)
                return null;
            //const int HdrLength = 0x4E;
            //var bmp = data.Skip(HdrLength).ToArray();            			
            using (var ms = new MemoryStream(data))
            {
                BitmapImage bi = new BitmapImage();
                try
                {
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.StreamSource = ms;
                    bi.EndInit();
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "SqlImageToBitmapImage");
                    Console.WriteLine(ex.Message);
                    return null;
                }
                return bi;
            }
        }

        // convert tu hinh co san xuong sql server dang binary
        public static byte[] ImageToBitmapImage(System.Drawing.Image imagefile)
        {
            using (var ms = new MemoryStream())
            {
                //ms.Write(hdrdefault, 0, hdrdefault.Length);
                imagefile.Save(ms, imagefile.RawFormat);
                return ms.ToArray();
            }
        }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return null;

            byte[] b = value as byte[];
            if (b != null)
                return SqlImageToBitmapImage(b);

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }




        #endregion
    }
}
